import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DateFormatService {

  constructor() { }

  static checkedDate(date: number | Date): Date{
    return typeof date === 'number' ? new Date(date) : date;
};

static getDayCountOfMonth(year: number, month: number): number{
    
    var /** @type {?} */ isLeapYear = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
    return [
        month === 1 && !isLeapYear,
        month === 1 && isLeapYear,
        !!([3, 5, 8, 10].find(function (num) { return num === month; })),
        true,
    ].reduce(function (pre, next, index) { return pre ? pre : (next ? 28 + index : 0); }, 0);
};

static getFirstDayOfMonth(date: number | Date): number{
    var /** @type {?} */ checkedDate = DateFormatService.checkedDate(date);
    checkedDate.setDate(1);
    return checkedDate.getDay();
};

static getCurrentMonthOffset(targetDate: number | Date): number{
    var /** @type {?} */ checkedDate:Date = DateFormatService.checkedDate(targetDate);
    var /** @type {?} */ currentDate = new Date();
    if (currentDate.getFullYear() !== checkedDate.getFullYear()) {
        return 0;
    }
    var /** @type {?} */ offset = currentDate.getMonth() - checkedDate.getMonth();
    return (offset > 1 || offset < -1) ? 0 : offset;
};

static moment(input: any, format: string): string{
    var /** @type {?} */ d = new Date(input);
    if (String(d) === 'Invalid Date')
        return '';
    var /** @type {?} */ makeReg = function (value:any) { return new RegExp("(" + value + ")"); };
    var /** @type {?} */ keys = ['M+', 'd+', 'h+', 'm+', 's+', 'q+', 'S'];
    var /** @type {?} */ values = [
        d.getMonth() + 1,
        d.getDate(),
        d.getHours(),
        d.getMinutes(),
        d.getSeconds(),
        Math.floor((d.getMonth() + 3) / 3),
        d.getMilliseconds(),
    ];
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    var /** @type {?} */ len = 0, /** @type {?} */ key, /** @type {?} */ val:any;
    while (len < keys.length) {
        key = keys[len];
        val = values[len];
        if (makeReg(key).test(format)) {
          if(RegExp.$1.length === 1){
            format = ((format)).replace(RegExp.$1,val );
          }else{
            format = ((format)).replace(RegExp.$1, ('00' + val).substr(('' + val).length));
          }
        }
        len++;
    }
    return format;
};

getTime(input?: any): number{
    var /** @type {?} */ date = new Date(input);
    if (String(date) === 'Invalid Date') {
        return 0;
    }
    return date.getTime();
};
}
